var util = {};

function getSessionId() {
  wx.login({
    success: r => {
      // console.log(r);
      // 发送 r.code 到后台换取 openId, sessionKey, unionId
      wx.request({
        url: getApp().globalData.url + 'member/autoLogin',
        data: {
          code: r.code
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
        method: 'POST',
        success: result => {
          // console.log(result);
          let resultData = result.data;
          if (resultData.success) {
            let data = resultData.data;
            getApp().globalData.sessionId = data.sessionId;
            getApp().globalData.isAdmin = data.admin;
          }
        }
      });
    }
  })
}

function myRequest(res) {
  let host = getApp().globalData.url;
  let sessionId = getApp().globalData.sessionId;
  wx.request({
    url: host + res.url,
    data: res.data ? res.data : {},
    header: {
      "Content-Type": "application/x-www-form-urlencoded",
      "Cookie": "JSESSIONID=" + sessionId
    },
    method: res.method ? res.method : 'POST',
    dataType: 'json',
    success: function(data) {
      if (data.data.code === "5") {
        getSessionId();
      }
      if (typeof res.success == "function") {
        res.success(data);
      }
    },
    fail: function() {
      if (typeof res.doFail == "function") {
        res.doFail();
      }
    },
    complete: function() {
      if (typeof res.doComplete == "function") {
        res.doComplete();
      }
    }
  });
}
util.request = myRequest, util.getSessionId = getSessionId, module.exports = util;